/**
 * Created by gongxun on 16/12/23.
 */

var HttpHelper = function(){
    var that = {};

    that.logXHREvents = function(xhr, callback){
        // Simple events
        ['loadstart', 'abort', 'error', 'load', 'loadend', 'timeout'].forEach(function (eventname) {
            xhr["on" + eventname] = function () {
                // cc.log("Event:" + eventname);

                //连接超时
                if (eventname == "error"){
                    // cc.log("Event:" + eventname);
                    cc.log("[http response] url:" + xhr.mRequestUrl + " error");
                    callback(-1, xhr);
                }else if(eventname == "timeout"){
                    // cc.log("Event:" + eventname);
                    cc.log("[http response] url:" + xhr.mRequestUrl + " timeout");
                    callback(-1, xhr);
                }
            };
        });

        // Special event
        xhr.onreadystatechange = function () {
            var body = xhr.responseText + "";
            if (body.length > 100){
                body = body.substr(0, 100) + "...";
            }
            body = body.replace(/[\r\n]/g, "");
            cc.log("[http response] url:" + xhr.mRequestUrl + " status:" + xhr.status + "len:" + body.length + " body:" + body);

            // var currentTime = mo.gameHelper.getMillisecond() + 5000;
            // while (mo.gameHelper.getMillisecond() < currentTime){
            //     var a = 1.011231;
            //     var b = 2.02121;
            //     var c = a * b;
            // }

            // cc.log("readyState:" + xhr.readyState + " status" + xhr.status);
            var code = -1;
            if (xhr.readyState == 4 && (xhr.status == 200)) {
                var httpStatus = xhr.statusText;
                var response = xhr.responseText;
                // cc.log("httpStatus:" + httpStatus);
                // cc.log("response:" + response);
                // cc.log("success");
                code = 0;
                callback(code, xhr);
            }else{
                callback(code, xhr);
            }
        };
    };

    //post
    that.sendPost = function (url, params, callback) {
        cc.log("[http post] url:" + url + " params:" + params);

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.mRequestUrl = url;
        xhr.open("POST", url);
        xhr.timeout = 6000;
        xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");

        that.logXHREvents(xhr, callback);
        xhr.send(params);
    };

    //post upload
    that.sendPostUpload = function (url, params, callback) {
        cc.log("[http post] url:" + url + " params:" + params);
        // cc.log("params len:" + params.length);

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.mRequestUrl = url;
        xhr.open("POST", url);
        xhr.timeout = 6000;
        // xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
        //请求头
        xhr.setRequestHeader("Host", "upload-z2.qiniu.com");
        xhr.setRequestHeader("User-Agant", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/51.0");
        xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        xhr.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
        xhr.setRequestHeader("Referer", "http://192.168.0.101/testgx");
        xhr.setRequestHeader("Connection", "keep-alive");
        xhr.setRequestHeader("Upgrade-Insecure-Requests", "1");
        //上传头
        xhr.setRequestHeader('Content-Type','multipart/form-data; boundary=' + "blob");
        xhr.setRequestHeader('Content-Length', params.length);

        that.logXHREvents(xhr, callback);
        xhr.send(params);
    };

    //get
    that.sendGet = function (url, callback) {
        cc.log("[http get] url:" + url);

        var xhr = cc.loader.getXMLHttpRequest();
        xhr.mRequestUrl = url;
        xhr.open("GET", url ,true);
        xhr.timeout = 6000;
        that.logXHREvents(xhr, callback);
        xhr.send();
    };

    //timestamp
    that.getTimestamp = function(){
        return mo.gameHelper.getTimestamp().toString();
    };

    //session
    that.getSession = function(){
        return mo.nativeConfig.getSession();
    };

    //uid
    that.getUid = function(){
        return mo.gameUserInfo.uid;
    };

    //返回channel
    that.getChannel = function(){
        if (cc.sys.os == "iOS"){
            return "2";
        }else if (cc.sys.os == "Android"){
            return "1";
        }else {
            return "3";
        }
    };

    return that;
};

mo.httpHelper = new HttpHelper();